//calc.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    result: "0",
    id1: "history",
    id2: "clear",
    id3: "back",
    id4: "div",
    id5: "num_7",
    id6: "num_8",
    id7: "num_9",
    id8: "mul",
    id9: "num_4",
    id10: "num_5",
    id11: "num_6",
    id12: "sub",
    id13: "num_1",
    id14: "num_2",

    id15: "num_3",
    id16: "add",
    id17: "negative",
    id18: "num_0",
    id19: "dot",
    id20: "equ",
    temp: "0",        //上次临时结果
    lastoper: "+",    //上次运算符
    flag: false       //上次非数字按钮标志
  },
  clickButton: function (e) {
    var data = this.data.result;
    var tmp = this.data.temp;
    var lastoper = this.data.lastoper;
    var noNumFlag = this.data.flag;

    if (e.target.id >= 'num_0' && e.target.id <= 'num_9') {
      //正常处理数字，后面拼接
      data += e.target.id.split("_")[1];
      if (this.data.result == '0' || noNumFlag) {
        //原值为0，或上次所按是 非数字按钮；
        data = e.target.id.split("_")[1];
      }
      noNumFlag = false;
    } else {
      //处理其他控制字符
      console.log(e.target.id);
      noNumFlag = true;
      if (e.target.id == "dot") {
        if (data.toString().indexOf(".") == -1) {
          data += ".";
        }
        //. 号也是数字一部分，因此要设置数字标记
        noNumFlag = false;
      } else if (e.target.id == "history") {
        console.log("点击了历史");
      } else if (e.target.id == "clear") {
        //清空上次操作相关属性
        data = 0;
        tmp = 0;
        lastoper = "+";
      } else if (e.target.id == "negative") {
        data = -1 * data;

      } else if (e.target.id == "back") {
        if (data.toString().length > 1) {
          data = data.substr(0, data.toString().length - 1);
        } else {
          data = 0;
        }
      } else if (e.target.id == "div") {
        data = calculate(tmp, lastoper, data);
        tmp = data;
        lastoper = "/";
      } else if (e.target.id == "mul") {
        data = calculate(tmp, lastoper, data);
        tmp = data;
        lastoper = "*";
      } else if (e.target.id == "add") {
        data = calculate(tmp, lastoper, data);
        tmp = data;
        lastoper = "+";
      } else if (e.target.id == "sub") {
        data = calculate(tmp, lastoper, data);
        tmp = data;
        lastoper = "-";
      } else if (e.target.id == "equ") {
        data = calculate(tmp, lastoper, data);
        //计算完成后清空上次操作相关属性
        tmp = 0;
        lastoper = "+";
      }
    }
    this.setData({
      result: data,
      temp: tmp,
      lastoper: lastoper,
      flag: noNumFlag
    })
  }
})
//四则运算函数
var calculate = function (data1, oper, data2) {
  var data;
  data1 = parseFloat(data1);
  data2 = parseFloat(data2);
  switch (oper) {
    case "+":
      data = data1 + data2;
      break;
    case "-":
      data = data1 - data2;
      break;
    case "*":
      data = data1 * data2;
      break;
    case "/":
      if (data2 != 0) {
        data = data1 / data2;
      } else {
        data = 0;
      }
      break;
  }
  return data;
}